package br.com.timecardforpeon.event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class EventSubscriber {

	private static final EventSubscriber INSTANCE = new EventSubscriber();
	
	private Map<Class<? extends Event<?>>, List<EventListener>> listeners = new HashMap<Class<? extends Event<?>>, List<EventListener>>();
	
	private EventSubscriber() {
	}
	
	public static EventSubscriber getInstance() {
		return INSTANCE;
	}
	
	public EventSubscriber addListener(Class<? extends Event<?>> eventClass, EventListener listener) {
		
		if (!this.listeners.containsKey(eventClass)) {
			this.listeners.put(eventClass, new ArrayList<EventListener>());
		}
		this.listeners.get(eventClass).add(listener);
		return this;
	}

	@SuppressWarnings("unchecked")
	public void publish(Event<?> event) {
		
		Class<? extends Event<?>> eventType = (Class<? extends Event<?>>) event.getClass();
		if (!this.listeners.containsKey(eventType)) {
			return;
		}
		
		List<EventListener> list = this.listeners.get(eventType);
		for (EventListener listener : list) {
			listener.onEventListener(event);
		}
	}
}